/**
 * 线程本地存储
 *
 * @author fireway
 * @since 2019年 01月 09日 星期三 07:33:37 CST
 */
package concurrency;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Accessor implements Runnable {
    private final int mId;

    public Accessor(int id) {
        mId = id;
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            ThreadLocalVariableHolder.increase();
            System.out.println(this);
            Thread.yield();
        }
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("#");
        sb.append(mId);
        sb.append(": ");
        sb.append(ThreadLocalVariableHolder.get());
        return sb.toString();
    }
}

public class ThreadLocalVariableHolder {
    private static ThreadLocal<Integer> mValue = new ThreadLocal<Integer>() {
        private Random mRand = new Random(47);

        @Override
        protected synchronized Integer initialValue() {
            return mRand.nextInt(10000);
        }
    };

    public static void increase() {
        mValue.set(mValue.get() + 1);
    }

    public static int get() {
        return mValue.get().intValue();
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            exec.execute(new Accessor(i));
        }

        try {
            TimeUnit.SECONDS.sleep(3);
            exec.shutdownNow();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
